<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018/10/22
 * Time: 7:21 PM
 */

namespace app\api\controller;

use Alipay\Alipayobj;
use app\common\model\Agent;
use app\common\model\Merchant;
use app\common\model\Paylog;
use app\common\model\Tklog;
use app\common\model\WxOpen;
use Wechat\Wxobjopen;
use Weixinpay\Wxtk;

class OfficialOrder extends Pub

{
    public function getorderreverse($param, $pay_fs)
    {
        try {

            if ($pay_fs || $pay_fs == "0") {
                switch ($pay_fs) {
                    case '0':
                        $rarr = $this->wxreverse($param);
                        break;
                    case '1':
                        $rarr = $this->alireverse($param);
                        break;
                    case '2':
                        $rarr = $this->wxreverse($param);
                        break;
                    case '3':
                        $rarr = $this->alireverse($param);
                        break;
                }
            } else {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '订单编号不存在';
                $rarr['result_code'] = 'FAIL';
                $rarr['result_msg'] = "订单编号不存在";
            }


        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = "系统错误" . $e->getMessage();
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = "系统错误" . $e->getMessage();
        }
        return $rarr;
    }

    public function getorderrefund($param, $pay_fs)
    {

        try {

            if ($pay_fs || $pay_fs == 0) {
                switch ($pay_fs) {
                    case '0':
                        $rarr = $this->wxorderrefund($param);
                        break;
                    case '1':
                        $rarr = $this->aliorderrefund($param);

                        break;
                    case '2':
                        $rarr = $this->wxorderrefund($param);
                        break;
                    case '3':
                        $rarr = $this->aliorderrefund($param);
                        break;
                    case '8':
                        $rarr = $this->wxorderrefund($param);
                        break;
                }
            } else {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '订单编号不存在';
                $rarr['result_code'] = 'FAIL';
                $rarr['result_msg'] = "订单编号不存在";
            }

        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();
        }
        return $rarr;
    }

    public function wxorderrefund($param)
    {

        try {

            $map['id'] = $param['merchantid'];
            $User = new Merchant();
            $Agent = new Agent();
            $WxOpen = new WxOpen();
            $Paylog = new Paylog();
            $config = $User->where($map)->find();
            $agent = $Agent->where(array('id' => $config['agent']))->find();
            $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
            $order = $Paylog->where('orderid', $param['out_trade_no'])->find();
            $options['wx_open_id'] = $agent['wx_open_id'];
            $weObj = new Wxtk($options);
            if (isset($param['client_source']) && $param['client_source'] !== 1) {
                $tk_orderid = $param['other_refund_no'];
                $params['client_source'] = $param['client_source'];
                $params['other_tk_orderid'] = $param['client_source'];
            } else {
                $tk_orderid = $this->getorderid($param['merchantid']);
            }
            $notice = $weObj->generateNonceStr();
            $weObj->setParameter('appid', $users['authorizer_appid']);
            $weObj->setParameter('mch_id', $agent['partnerid']);
            $weObj->setParameter('sub_mch_id', $config['sub_mch_id']);
            $weObj->setParameter('nonce_str', $notice);
            $weObj->setParameter('refund_desc', isset($param['refund_desc']) ? $param['refund_desc'] : 0);
            $weObj->setParameter('out_trade_no', $param['out_trade_no']);
            $weObj->setParameter('out_refund_no', $tk_orderid);
            $weObj->setParameter('total_fee', $order['price'] * 100);
            $weObj->setParameter('refund_fee', $param['refund_fee'] * 100);
            $sss = $weObj->create_refund_xml($agent['partnerkey']);
            $url = 'https://api.mch.weixin.qq.com/secapi/pay/refund';
            $responseXml = $weObj->curl_post_ssl($url, $sss);

            $responseObj = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
            //转换成数组
            $params['orderid'] = $param['out_trade_no'];
            $params['mid'] = $param['merchantid'];
            $params['addtime'] = time();
            $params['action_user'] = $param['device_id'];
            $params['tk_fs'] = $param['source'];
            $params['pid'] = $order['id'];
            $params['refund_fee'] = $param['refund_fee'];
            $params['tk_orderid'] = $tk_orderid;


            $responseArr = ( array )$responseObj;

            if ($responseArr['return_code'] == 'SUCCESS' && $responseArr['result_code'] == "SUCCESS") {
                if ($responseArr['return_msg'] == 'OK') {
                    $rarr['return_code'] = "SUCCESS";
                    $rarr['result_code'] = "SUCCESS";
                    $rarr['return_msg'] = "退款成功";
                    $rarr['result_msg'] = "退款成功";
                    $rarr['out_trade_no'] = $order['orderid'];
                    $rarr['out_refund_no'] = $responseArr['out_refund_no'];
                    $rarr['trade_no'] = $order['trade_no'];
                    $rarr['total_fee'] = $order['price'];//支付金额
                    $rarr['refund_fee'] = $param['refund_fee'];//退款金额
                    $rarr['channel'] = $order['pay_fs'];//支付方式
                    $params['tk_status'] = 1;
                    $params['sys_orderid'] = $responseArr['refund_id'];
                    if ($order['price'] == $order['tk_price'] + $param['refund_fee']) {
                        $sedata['pay_statu'] = 2;
                        $sedata['tk_status'] = 1;
                    } else {
                        $sedata['pay_statu'] = 3;
                        $sedata['tk_status'] = 2;
                    }
                    $sedata['tk_price'] = $order['tk_price'] + $param['refund_fee'];
                    $Paylog->save($sedata, ['orderid' => $order['orderid']]);
                } else {
                    $rarr['return_code'] = "SUCCESS";
                    $rarr['result_code'] = "FAIL";
                    $rarr['return_msg'] = $responseArr['return_msg'];
                    $rarr['result_msg'] = $responseArr['return_msg'];
                    $params['tk_status'] = 3;
                }
                $params['tk_info'] = json_encode($responseArr);
            } else {
                if (isset($responseArr['err_code_des'])) {
                    $errmsg = $responseArr['err_code_des'];
                } elseif (isset($responseArr['return_msg'])) {
                    $errmsg = translate($responseArr['return_msg']);
                } else {
                    $errmsg = "未知错误";
                }
                $rarr['return_code'] = "SUCCESS";
                $rarr['result_code'] = "FAIL";
                $rarr['return_msg'] = $errmsg;
                $rarr['result_msg'] = $errmsg;
            }
            $params['tk_info'] = json_encode($responseArr);
            $Tklog = new Tklog();

            $Tklog->save($params);
//                } else {
//                    $rarr['return_code'] = "SUCCESS";
//                    $rarr['result_code'] = "FAIL";
//                    $rarr['return_msg'] = "该账户没有退款权限";
//                    $rarr['result_msg'] = "该账户没有退款权限";
//                }
//            } else {
//                $rarr['return_code'] = "SUCCESS";
//                $rarr['result_code'] = "FAIL";
//                $rarr['return_msg'] = "退款密码错误";
//                $rarr['result_msg'] = "退款密码错误";
//            }

        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();
        }
        return $rarr;
    }

    public function order_refund_query($param, $pay_fs)
    {
        try {

            if ($pay_fs || $pay_fs == "0") {
                switch ($pay_fs) {
                    case '0':
                        $rarr = $this->wx_order_refund_query($param);
                        break;
                    case '1':
                        $rarr = $this->ali_order_refund_query($param);
                        break;
                    case '2':
                        $rarr = $this->wx_order_refund_query($param);
                        break;
                    case '3':
                        $rarr = $this->ali_order_refund_query($param);
                        break;
                    case '8':
                        $rarr = $this->wx_order_refund_query($param);
                        break;
                }

            } else {
                $rarr['return_code'] = "FAIL";
                $rarr['result_code'] = 'FAIL';
                $rarr['return_msg'] = '订单编号不存在';

                $rarr['result_msg'] = "订单编号不存在";
            }

        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();
        }
        return $rarr;
    }

    public function wx_order_refund_query($param)
    {
        $Paylog = new Paylog();
        $mab['pay_statu'] = array('neq', 0);

        $mab['orderid'] = $param['out_trade_no'];

        $paylog = $Paylog->where($mab)->find();

        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $map['id'] = $param['merchantid'];

        $config = $Merchant->where($map)->find();
        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
        $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();

        $options = array(
            'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
            'partnerid' => $agent['partnerid'], // 财付通商户身份标识
            'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
        );

        $weObj = new Wxobjopen($options);
        $appid = $users['authorizer_appid'];
        $mch_id = $agent['partnerid'];
        $out_trade_no = $paylog['orderid'];
        $out_refund_no = $param['refund_no'];
        $nonce_str = $weObj->generateNonceStr();
        $sub_mch_id = $config['sub_mch_id'];
        $sub_appid = $userwx['authorizer_appid'];
        $arrdata = array(
            "appid" => $appid,
            "mch_id" => $mch_id,
            "sub_appid" => $sub_appid,
            "out_refund_no" => $out_refund_no,
            "sub_mch_id" => $sub_mch_id,
            "nonce_str" => $nonce_str,
            "out_trade_no" => $out_trade_no
        );
        $pay_xml = $weObj->createWxPackageXml($arrdata);
//        $pay_xml = $weObj->createOrderrefundXml($appid, $mch_id, $sub_appid, $sub_mch_id, $out_refund_no, $out_trade_no, $nonce_str);
        $payorder_xml = $weObj->getPayRefundQuery($pay_xml);
        $rarr['return_code'] = "SUCCESS";
        if ($payorder_xml['return_code'] == "SUCCESS") {
            if ($payorder_xml['result_code'] == "SUCCESS") {
                $rarr['result_code'] = "SUCCESS";
                $rarr['return_msg'] = "查询成功";

                $rarr['result_msg'] = "查询成功";
                $rarr['out_trade_no'] = $paylog['orderid'];
                $rarr['channel'] = $paylog['pay_fs'];
                $rarr['refund_no'] = $payorder_xml["out_refund_no_0"];
                $rarr['out_refund_no'] = $payorder_xml["out_refund_no_0"];
                $rarr['refund_fee'] = $payorder_xml["refund_fee_0"] / 100;
                $rarr['trade_no'] = $paylog['trade_no'];

            } else {
                $rarr['result_code'] = "FAIL";
                if (isset($payorder_xml['result_msg'])) {
                    $rarr['result_msg'] = $payorder_xml['result_msg'];
                    $rarr['return_msg'] = $payorder_xml['return_msg'];
                } elseif (isset($payorder_xml['err_code'])) {
                    $rarr['result_msg'] = $payorder_xml['err_code'];
                    $rarr['return_msg'] = $payorder_xml['err_code'];
                }
            }

        } else {
            $rarr['result_code'] = "FAIL";
            if (isset($payorder_xml['result_msg'])) {
                $rarr['result_msg'] = $payorder_xml['result_msg'];
                $rarr['return_msg'] = $payorder_xml['return_msg'];

            } elseif ($payorder_xml['err_code']) {
                $rarr['result_msg'] = $payorder_xml['err_code'];
                $rarr['return_msg'] = $payorder_xml['err_code'];
            }
        }
        return $rarr;

    }

    public function ali_order_refund_query($param)
    {
        try {
            $User = new Merchant();
            $Agent = new Agent();
            $Paylog = new Paylog();
            $users = $User->where(array('id' => $param['merchantid']))->find();
            $agent = $Agent->where(array('id' => $users['agent']))->find();
            $mab['pay_statu'] = array('neq', 0);
            $mab['orderid'] = $param['out_trade_no'];
            $paylog = $Paylog->where($mab)->find();
            if ($paylog) {
                $options = array(
                    'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
                    'rsaPrivateKey' => $agent['ali_app_key'],

                );
                $aliObj = new Alipayobj($options);
                $data['app_id'] = $agent['ali_app_id'];
                $data['method'] = "alipay.trade.fastpay.refund.query";
                $data['charset'] = "UTF-8";
                $data['sign_type'] = "RSA2";
                $data['timestamp'] = date('Y-m-d H:i:s');
                $data['version'] = "1.0";
                $data['app_auth_token'] = $users['ali_merid'];
                $data['biz_content'] = json_encode(array(
//                'trade_no' =>"2018052821001004920505662953",
                    'out_trade_no' => $paylog['orderid'],
                    'out_request_no' => $param['refund_no'],

                ));
                $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
                $data['sign'] = $signContent;
                $sj = $aliObj->scanpay($data);

                $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);
                $rarr['return_code'] = "SUCCESS";

                if ($content['alipay_trade_fastpay_refund_query_response']['code'] == "10000") {
                    if (isset($content['alipay_trade_fastpay_refund_query_response']['trade_no'])) {
                        $rarr['result_code'] = "SUCCESS";
                        $rarr['return_msg'] = "查询成功";
                        $rarr['result_msg'] = "查询成功";
                        $rarr['out_trade_no'] = $paylog['orderid'];
                        $rarr['channel'] = $paylog['pay_fs'];
                        $rarr['refund_no'] = $param['refund_no'];
                        $rarr['refund_fee'] = $content['alipay_trade_fastpay_refund_query_response']['refund_amount'];
                        $rarr['trade_no'] = $paylog['trade_no'];


                    } else {
                        $rarr['result_code'] = "FAIL";
                        if (isset($content['alipay_trade_fastpay_refund_query_response']['sub_msg'])) {
                            $rarr['result_msg'] = $content['alipay_trade_fastpay_refund_query_response']['sub_msg'];
                            $rarr['return_msg'] = $content['alipay_trade_fastpay_refund_query_response']['sub_msg'];
                        } else {
                            $rarr['result_msg'] = "查询失败";
                            $rarr['return_msg'] = "查询失败";
                        }
                    }
                }
            }

        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['result_code'] = "FAIL";
            $rarr['return_msg'] = "系统错误" . $e->getMessage();
            $rarr['result_msg'] = "系统错误" . $e->getMessage();
        }
        return $rarr;
    }

    public function aliorderrefund($param)
    {
        try {
//            $mas['mid'] = $param['merchid'];
//            $mas['device_code'] = $param['device_code'];
//            $DeviceUser = new DeviceMicro();
//            $deviceuser = $DeviceUser->where($mas)->find();
//
//            if ($deviceuser['tk_pass'] == MD5($param['tk_pass'])) {
//                if ($deviceuser['is_tk'] == 1) {
            $User = new Merchant();
            $Agent = new Agent();
            $Patlog = new Paylog();
            $users = $User->where(array('id' => $param['merchantid']))->find();
            $agent = $Agent->where(array('id' => $users['agent']))->find();

            $mab['orderid'] = $param['out_trade_no'];


            $order = $Patlog->where($mab)->find();
            if ($order) {
                $options = array(

                    'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
                    'rsaPrivateKey' => $agent['ali_app_key'],

                );

                $aliObj = new Alipayobj($options);

                $price = $param['refund_fee'];
                $out_trade_no = $order['orderid'];
                if (isset($param['client_source']) && $param['client_source'] !== 1) {
                    $out_request_no = $param['other_refund_no'];
                    $params['client_source'] = $param['client_source'];
                    $params['other_tk_orderid'] = $param['client_source'];
                } else {
                    $out_request_no = $this->getorderid($param['merchantid']);
                }

                $total_fee = $price;
                $data['app_id'] = $agent['ali_app_id'];
                $data['method'] = "alipay.trade.refund";
                $data['charset'] = "UTF-8";
                $data['sign_type'] = "RSA2";
                $data['timestamp'] = date('Y-m-d H:i:s');
                $data['version'] = "1.0";
                $data['app_auth_token'] = $users['ali_merid'];
                $data['biz_content'] = json_encode(array(
                    'out_trade_no' => $out_trade_no,
                    'refund_amount' => $total_fee,
                    'refund_reason' => isset($data['refund_desc']) ? $data['refund_desc'] : 0,
                    'out_request_no' => $out_request_no,
                    'operator_id' => isset($param['device_id']) ? $param['device_id'] : "",
                    'alipay_store_id' => $users['ali_store_id'],

                ));
//                return $data;
                $params['orderid'] = $order['orderid'];
                $params['mid'] = $param['merchantid'];
                $params['addtime'] = time();
                $params['action_user'] = isset($param['device_id']) ? $param['device_id'] : "";
                $params['tk_fs'] = $param['source'];
                $params['pid'] = $order['id'];
                $params['refund_fee'] = $param['refund_fee'];
                $params['tk_orderid'] = $out_request_no;
                $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
                $data['sign'] = $signContent;
                $sj = $aliObj->scanpay($data);
                $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);

                if ($content['alipay_trade_refund_response']['code'] == 10000) {
                    if ($content['alipay_trade_refund_response']['msg'] == "Success") {
                        $rarr['return_code'] = "SUCCESS";
                        $rarr['result_code'] = "SUCCESS";
                        $rarr['return_msg'] = "退款成功";
                        $rarr['result_msg'] = "退款成功";
                        $rarr['out_trade_no'] = $order['orderid'];
                        $rarr['out_refund_no'] = $out_request_no;
                        $rarr['trade_no'] = $order['trade_no'];
                        $rarr['total_fee'] = $order['price'];//支付金额
                        $rarr['refund_fee'] = $param['refund_fee'];//退款金额
                        $rarr['channel'] = $order['pay_fs'];//支付方式
                        if ($order['price'] == $order['tk_price'] + $param['refund_fee']) {
                            $sedata['pay_statu'] = 2;
                            $sedata['tk_status'] = 1;
                        } else {
                            $sedata['pay_statu'] = 3;
                            $sedata['tk_status'] = 2;
                        }
                        $sedata['tk_price'] = $order['tk_price'] + $param['refund_fee'];
                        $Patlog->save($sedata, ['orderid' => $param['out_trade_no']]);
//                        $param['sys_orderid'] = $content['alipay_trade_refund_response']['trade_no'];
                        $params['tk_status'] = 1;
                    } else {
                        $rarr['return_code'] = "SUCCESS";
                        $rarr['result_code'] = "FAIL";
                        $rarr['return_msg'] = $content['alipay_trade_refund_response']['sub_code'];
                        $rarr['result_msg'] = $content['alipay_trade_refund_response']['sub_msg'];
                        $params['tk_status'] = 3;
                    }
                } else {
                    $rarr['return_code'] = "SUCCESS";
                    $rarr['result_code'] = "FAIL";
                    $rarr['return_msg'] = $content['alipay_trade_refund_response']['sub_code'];
                    $rarr['result_msg'] = $content['alipay_trade_refund_response']['sub_msg'];
                }
                $params['tk_info'] = json_encode($content);
                $Tklog = new Tklog();

                $Tklog->save($params);
            } else {
                $rarr['return_code'] = "SUCCESS";
                $rarr['result_code'] = "FAIL";
                $rarr['return_msg'] = "订单编号不存在";
                $rarr['result_msg'] = "订单编号不存在";

            }
//                } else {
//                    $arr = array('code' => 80002, 'message' => '该登录账户没有退款权限');
//                }
//            } else {
//                $arr = array('code' => 80001, 'message' => '退款密码错误');
//            }

        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['result_code'] = "FAIL";
            $rarr['return_msg'] = "系统错误" . $e->getMessage();
            $rarr['result_msg'] = "系统错误" . $e->getMessage();
        }

        return $rarr;
    }


    //撤销订单操作
    public function wxreverse($param)
    {
//        $data['merchid']=602;
//        $data['orderid']='123';
        try {
            $map['id'] = $param['merchantid'];
            $User = new Merchant();
            $Agent = new Agent();
            $WxOpen = new WxOpen();
            $config = $User->where($map)->find();

            $agent = $Agent->where(array('id' => $config['agent']))->find();
            $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
            $options['wx_open_id'] = $agent['wx_open_id'];
            $weObj = new Wxtk($options);
            $notice = $weObj->generateNonceStr();
            $weObj->setParameter('appid', $users['authorizer_appid']);
            $weObj->setParameter('mch_id', $agent['partnerid']);
            $weObj->setParameter('sub_mch_id', $config['sub_mch_id']);
            $weObj->setParameter('nonce_str', $notice);
            $weObj->setParameter('out_trade_no', $param['out_trade_no']);
            $sss = $weObj->create_refund_xml($agent['partnerkey']);
            $url = 'https://api.mch.weixin.qq.com/secapi/pay/reverse';
            $responseXml = $weObj->curl_post_ssl($url, $sss);
            $responseObj = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
            $responseArr = ( array )$responseObj;
            if ($responseArr['return_code'] == "SUCCESS" && $responseArr['result_code'] = "SUCCESS") {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = "";
                $rarr['result_code'] = 'SUCCESS';
                $rarr['result_msg'] = "订单撤销成功";
                $rarr['out_trade_no'] = $param['out_trade_no'];
                $sdata['pay_statu'] = 8;
                $Paylog = new Paylog();
                $Paylog->save($sdata, ['orderid' => $param['out_trade_no']]);

            } else {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = "";
                $rarr['result_code'] = 'FAIL';
                $rarr['result_msg'] = "订单无法撤销";
            }

        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = "系统错误" . $e->getMessage();
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = "系统错误" . $e->getMessage();
        }
        return $rarr;
    }

    public function alireverse($param)
    {
        try {

            $User = new Merchant();
            $Agent = new Agent();
            $users = $User->where(array('id' => $param['merchantid']))->find();
            $agent = $Agent->where(array('id' => $users['agent']))->find();
            $options = array(

                'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
                'rsaPrivateKey' => $agent['ali_app_key'],

            );

            $aliObj = new Alipayobj($options);
            $out_trade_no = $param['out_trade_no'];
            $data['app_id'] = $agent['ali_app_id'];
            $data['method'] = "alipay.trade.cancel";
            $data['charset'] = "UTF-8";
            $data['sign_type'] = "RSA2";
            $data['timestamp'] = date('Y-m-d H:i:s');
            $data['version'] = "1.0";
            $data['app_auth_token'] = $users['ali_merid'];
            $data['biz_content'] = json_encode(array(
                'out_trade_no' => $out_trade_no,

            ));
            $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
            $data['sign'] = $signContent;
            $sj = $aliObj->scanpay($data);

            $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);
            if ($content['alipay_trade_cancel_response']['code'] == 10000) {
                if ($content['alipay_trade_cancel_response']['msg'] == "Success") {
                    $rarr['return_code'] = "SUCCESS";
                    $rarr['return_msg'] = "";
                    $rarr['result_code'] = 'SUCCESS';
                    $rarr['result_msg'] = "订单撤销成功";
                    $rarr['out_trade_no'] = $param['out_trade_no'];
                    $sdata['pay_statu'] = 8;
                    $Paylog = new Paylog();
                    $Paylog->save($sdata, ['orderid' => $param['out_trade_no']]);
                } else {
                    $rarr['return_code'] = "SUCCESS";
                    $rarr['return_msg'] = "";
                    $rarr['result_code'] = 'FAIL';
                    $rarr['result_msg'] = "订单无法撤销";
                }
            } else {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = "";
                $rarr['result_code'] = 'FAIL';
                $rarr['result_msg'] = "订单无法撤销";
            }
        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = "系统错误" . $e->getMessage();
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = "系统错误" . $e->getMessage();
        }
        return $rarr;
    }

    public function create_wx_order($param)
    {
        $out_trade_no = $this->getorderid($param['merchantid']);;
        $sub_openid = $param['sub_openid'];
        $data['orderid'] = $out_trade_no;
        $data['mid'] = $param['merchantid'];
//            $data['openid'] = request()->post('openid');
        $data['openid'] = $param['sub_openid'];
        $data['pay_statu'] = 0;
        $data['add_time'] = time();
        $data['attach'] = $param['attach'];;
        if (isset($param['trade_no'])) {
            $data['trade_no'] = $param['trade_no'];;
        }
        $Paylog = new Paylog();
        $Paylog->save($data);

        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $map['id'] = $param['merchantid'];
        $config = $Merchant->where($map)->find();

        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();

        $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
        $options = array(
            'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
            'partnerid' => $agent['partnerid'], // 财付通商户身份标识
            'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
        );
        $weObj = new Wxobjopen($options);

        $yf_price = $param['total_fee'];
//        $zkarr['merchantid'] = $param['merchantid'];
//        $zkarr['openid'] = $param['sub_openid'];
//        $zkarr['total_fee'] = $yf_price;
//        $zkarr['orderid'] =$out_trade_no;;

        $zk_price = 0;

        $pay_fees = $yf_price - $zk_price;

        $data2['price'] = $pay_fees;

        $Paylog->save($data2, ['orderid' => $out_trade_no]);

        $appid = $users['authorizer_appid'];
        $mch_id = $agent['partnerid'];

        $body = "快捷支付";
        $sub_mch_id = $config['sub_mch_id'];
        $sub_appid = $userwx['authorizer_appid'];
        $total_fee = $pay_fees * 100;
        $openid = "";
//            $openid = request()->post('openid');
        $notify_url = 'https://os.wunengkeji.com/api.php';
        $spbill_create_ip = $_SERVER["REMOTE_ADDR"];

        $nonce_str = $weObj->generateNonceStr();
        $param_data['appid'] = $appid;
        $param_data['sub_appid'] = $sub_appid;
        $param_data['mch_id'] = $mch_id;
        $param_data['sub_mch_id'] = $sub_mch_id;
        $param_data['nonce_str'] = $nonce_str;
        $param_data['body'] = $body;
        $param_data['out_trade_no'] = $out_trade_no;
        $param_data['total_fee'] = $total_fee;
        $param_data['spbill_create_ip'] = $spbill_create_ip;
        $param_data['notify_url'] = $notify_url;
        $param_data['openid'] = $openid;
        $param_data['sub_openid'] = $sub_openid;
        $param_data['attach'] = $param['attach'];
        $param_data['trade_type'] = "JSAPI";
        $pay_xml = $weObj->createWxPackageXml($param_data);
//        $pay_xml = $weObj->createPackageXml2($appid, $sub_appid, $mch_id, $sub_mch_id, $nonce_str, $body, $out_trade_no, $total_fee, $spbill_create_ip, $notify_url, $openid, $sub_openid);

        $pay_xml = $weObj->get_pay_id($pay_xml);
        if ($pay_xml['return_code'] == "SUCCESS") {
            $prepay_id = $pay_xml['prepay_id'];
            $jsApiObj["appId"] = $appid;
            $timeStamp = time();
            $jsApiObj["timeStamp"] = "$timeStamp";
            $jsApiObj["nonceStr"] = $nonce_str;
            $jsApiObj["package"] = "prepay_id=" . $prepay_id;
            $jsApiObj["signType"] = "MD5";
            $jsApiObj["paySign"] = $weObj->getPaySignature($jsApiObj);
            $rarr['return_code'] = "SUCCESS";
            $rarr['return_msg'] = '';
            $rarr['result_code'] = 'SUCCESS';
            $rarr['result_msg'] = '';
            $rarr['out_trade_no'] = $out_trade_no;
            $rarr['info'] = $jsApiObj;
        } else {
            $rarr['return_code'] = "SUCCESS";
            $rarr['return_msg'] = '';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = $pay_xml['return_msg'];
        }

        return $rarr;
    }
}